<?php
/**
 * 客户端后台运行保存用户相关数据
 * User: csyr
 * Date: 16/6/28
 * Time: 上午10:28
 */

namespace Home\Controller;

use Common\Library\BusinessException;
use Common\Library\Constant;
use Common\Library\Http\Request;
use Common\Library\Http\Response;
use Think\Controller;
use Think\Log;
use Home\Model\MerchantModel;


class SystemController extends Controller
{
    public function __construct() {
        parent::__construct();

        try {
            Request::parse();
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
            $this->ajaxReturn($ret);
        }
    }

    /**
     * 保存用户手机联系人信息
     */
    public function saveCustomerContact()
    {
        try {
            $customerId = I('post.customer_id', 0);
            $contactName = I("post.contact_name",'');
            $contactPhone = I("post.contact_phone", '');
            $group = I("post.group", '');
            $nick = I("post.nick", '');
            $memo = I("post.memo", '');
            if (empty($customerId) || empty($contactName) || empty($contactPhone)) {
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            $ret = Constant::getReturn(Constant::FAILED);

            $contactModel = D("CustomerContact");
            if ($contact = $contactModel->checkContactExists($customerId, $contactPhone)) {
                $ret = Constant::getReturn(Constant::SUCCESS);
            }
            else
            {
                $time = time();
                $data = [
                    'customer_id'=>$customerId,
                    'contact_name'=>$contactName,
                    'contact_phone'=>$contactPhone,
                    'group'=>$group,
                    'nick'=>$nick,
                    'memo'=>$memo,
                    'add_time'=>$time
                ];
                $insertId = $contactModel->add($data);
                Log::borrow_write("******|saveCustomerContact".$customerId."|app推资料|保存用户手机联系人信息|结果：".$insertId."****：");
                if ($insertId) {
                    $ret = Constant::getReturn(Constant::SUCCESS);
                }
            }
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        $this->ajaxReturn($ret);
    }

    /**
     * 批量保存联系人信息
     * @throws \Think\Exception
     */
    public function saveContacts()
    {
        try {
            $customerId = I('post.customer_id', 0, 'int');
            D('Customer')->has($customerId);

            $contactList = I('post.contact_list');

            if (!$contactList || !is_array($contactList)) {
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            $CustomerContact = D('CustomerContact');
            $data = $phoneList = [];
            $time = time();
            foreach ($contactList as $contact) {
                $contactPhone = $contact['contact_phone'];
                /*$_data = [
                    'customer_id' => $customerId,
                    'contact_phone' => $contactPhone,
                ];*/
                if (!$contactPhone/* || isset($phoneList[$contactPhone]) || $CustomerContact->has($_data)*/) {
                    continue;
                }

                $phoneList[$contactPhone] = '';
                $data[] = [
                    'customer_id' => $customerId,
                    'contact_name' => $contact['contact_name'],
                    'contact_phone' => $contact['contact_phone'],
                    'group' => $contact['group']?$contact['group']:'',
                    'nick' => $contact['nick']?$contact['nick']:'',
                    'memo' => $contact['memo']?$contact['memo']:'',
                    'add_time' => $contact['add_time']?$contact['add_time']:$time,
                ];
            }

            if ($data && !$CustomerContact->addAll($data)) {
                BusinessException::throwException(Constant::FAILED);
            }
            Log::borrow_write("******|saveCustomerContact".$customerId."|app推资料|批量保存联系人信息");

            $ret = Constant::getReturn(Constant::SUCCESS);
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /**
     * 保存通话记录
     */
    public function saveCallRecord() {
        try {
            $customerId = I('post.customer_id', '', 'int');
            D('Customer')->has($customerId);

            $recordList = I('post.record_list');

            if (!$recordList || !is_array($recordList)) {
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            //获取用户上次保存通话记录的时间
            $callRecord = M('CustomerCallRecord')->field('id,add_time')->order(['id' => 'desc'])->find();
            $lastSaveTime = isset($callRecord['add_time']) ? (int)$callRecord['add_time'] : 0;

            $data = [];
            foreach ($recordList as $record) {
                $phoneNumber = $record['phone_number'];
                if (!$phoneNumber) {
                    continue;
                }

                $data[] = [
                    'customer_id' => $customerId,
                    'phone_number' => $phoneNumber,
                    'in_out' => $record['in_out'],
                    'duration_time' => $record['duration_time'],
                    'call_time' => $record['call_time'],
                    'add_time' => time(),
                ];
            }

            if ($data && !M('CustomerCallRecord')->addAll($data)) {
                BusinessException::throwException(Constant::FAILED);
            }
            Log::borrow_write("******|saveCustomerContact".$customerId."|app推资料|保存通话记录");


            $ret = Constant::getReturn(Constant::SUCCESS);
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        $ret['data'] = ['last_save_time' => $lastSaveTime];
        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /**
     * 保存用户短信
     */
    public function saveSMS() {
        try {
            $customerId = I('post.customer_id', 0, 'int');
            D('Customer')->has($customerId);
            $contactList = I('post.sms_list');
            if (!$customerId || !is_array($contactList)) {
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            $customerSms = D('CustomerSms');
            $data = [];
            foreach ($contactList as $contact)
            {
                $data[] = [
                    'customer_id'=>$customerId,
                    'address'=>$contact['address']?$contact['address']:'',
                    'person'=>$contact['person']?$contact['person']:'',
                    'body'=>$contact['body']?$contact['body']:'',
                    'date'=>$contact['date']?$contact['date']:'',
                    'type'=>$contact['type']?$contact['type']:''
                ];
            }

            if ($data && !$customerSms->addAll($data)) {
                BusinessException::throwException(Constant::FAILED);
            }
            Log::borrow_write("******|saveSMS".$customerId."|app推资料|批量保存联系人短信");
            $ret = Constant::getReturn(Constant::SUCCESS);
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        $this->ajaxReturn($ret);
    }
      /*** 检查版本更新 ***/
    public function checkUpgrade() {
        try {
            $id = I('post.id', '', 'int'); //用户或商户ID
            $appVersion = I('post.current_version', '', 'string');
            //1:android客户端，2:android商户端，3:ios客户端，4:ios商户端，5:winphone客户端，6:phone商户端 【10~19表示公司内部使用】 10:市场小工具
            $appType = I('post.app_type', '', 'int');
            $arr=[1,2,3,8,10];
            if(!in_array($appType,$arr)){
                Log::pay_write('+checkUpgrade--apptype重新复制：'.$appType);
                $appType=1;
            }
            if (1 === $appType) {
                /* channel_id渠道号,device_id设备id*/
                $channel_id = I('post.channel_id', '', 'string');
                $device_id = I('post.device_id', '', 'string');
                $clinetidList = C("CLINET_ID_LIST");//渠道号
                $clinetidStr = $clinetidList[$channel_id];//解密之后的渠道号
                //下载激活记录表入库
                $info = D('Customer')->addClientUuid($device_id, $clinetidStr);
                // 客户端检查升级
            } elseif (2 === $appType) {
                // 商户端检查升级
            } elseif (3 === $appType) {
                /* channel_id渠道号,device_id设备id*/
                $channel_id = I('post.channel_id', '', 'string');
                $device_id = I('post.device_id', '', 'string');
                $clinetidList = C("CLINET_ID_LIST");//渠道号
                $clinetidStr = $clinetidList[$channel_id];//解密之后的渠道号
                //下载激活记录表入库
                $info = D('Customer')->addClientUuid($device_id, $clinetidStr);
                // 客户端检查升级
            } elseif (8 === $appType){
                //$mobile = I('post.mobile');//用户手机号
                //$customer_id = I('post.customer_id');//用户id
                //$device_id = I('post.device_id', '', 'string');//设备id
                //$clinetidStr = '0';//渠道号
                //$info = D('Customer')->addClientUuid($device_id, $clinetidStr,$customer_id,$mobile);//写入统计表
            } elseif (10 === $appType){
            } else {
                Log::pay_write('+checkUpgrade apptype不在范围+ =');
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            $currentVersion = Constant::$APP_VERSION;
            
            if (!isset($currentVersion[$appType])) {
                Log::pay_write('++ checkUpgrade+++apptypeisset++ =');
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            /*
            $appArr = explode('.', $appVersion);
            $curArr = explode('.', $currentVersion[$appType]);
            $upd = false;
            foreach ($appArr as $k=>$v){
                if (intval($v) < intval($curArr[$k])) {
                    $upd = true;
                    break;
                }
            }*/
            $upd = false;
            if(version_compare($appVersion,$currentVersion[$appType],'<') ) {
                $upd = true;
            }
            if(!$upd){
                BusinessException::throwException(Constant::APP_UP_TO_DATE);
            }
            $ret = Constant::getReturn(Constant::SUCCESS);
			/*未标识来源|默认是百度来源*/
			if(!$clinetidStr){
				$clinetidStr='baidu';
			}
            if (1 == $appType) {
                 $downloadUrl = 'http://onat9tcj8.bkt.clouddn.com/zqh_2.0.7_17-12-14_207_'.$clinetidStr.'-zqh';
                 // @todo 上线后可以完善升级信息。
                /* if($appVersion>='1.1.8') {
                $ret['data'] = [
                    'app_type' => $appType,
                    'download_url' => $downloadUrl,
                    'introduction' => <<<EOF
                    1.部分bug修复
                    EOF
                    ,
                    'force_upgrade' => false,
                ];
                } else {*/
                $ret['data'] = [
                    'app_type' => $appType,
                    'download_url' => $downloadUrl,
                    'introduction' => <<<EOF
1.产品升级
EOF
                    ,
                    'force_upgrade' => true,
                    //'force_upgrade' => false,
                ];
                
                //}
            } elseif($appType == 3) {
                // @todo 上线后可以完善升级信息。
                $ret['data'] = [
                    'app_type' => $appType,
                    // 'download_url' => $downloadUrl,
                    'introduction' => <<<EOF
1.产品升级
EOF
                    ,
                    'force_upgrade' => true,
                    //'force_upgrade' => false,
                ];
            } elseif($appType == 8) {
                $downloadUrl = 'http://onat9tcj8.bkt.clouddn.com/zqh_2.0.7_17-12-14_207_'.$clinetidStr.'-zqh';
                // @todo 上线后可以完善升级信息。
                $ret['data'] = [
                    'app_type' => $appType,
                    'download_url' => $downloadUrl,
                    'introduction' => <<<EOF
1.产品升级
EOF
                    ,
                    'force_upgrade' => true,
                    //'force_upgrade' => false,
                ];
            } else {
                $downloadUrl = 'http://onat9tcj8.bkt.clouddn.com/zqh_2.0.7_17-12-14_207_'.$clinetidStr.'-zqh';
                // @todo 上线后可以完善升级信息。
                $ret['data'] = [
                    'app_type' => $appType,
                    'download_url' => $downloadUrl,
                    'introduction' => <<<EOF
1.产品升级
EOF
                    ,
                    'force_upgrade' => true,
                ];
            }
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        } 
        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    public function getLastSaveCallRecordTime() {
        try {
            $customerId = I('customer_id', 0, 'int');
            D('Customer')->has($customerId);

            $callRecord = M('CustomerCallRecord')->order(['add_time' => 'desc'])->find();
            $lastSaveTime = isset($callRecord['add_time']) ? (int)$callRecord['add_time'] : 0;

            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data'] = [
                'customer_id' => $customerId,
                'last_save_time' => $lastSaveTime,
            ];
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /****** 获取商户类型 ******/
    public function getMerchantTypeList(){
        try{
            $province = I('post.province_name');
            $city = I('post.city_name');
            $county = I('post.county_name');

            if(!$province || !$city || !$county){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            //按区县获取配置的商户类型
            $res = D('Merchant')->getTermsList($county, 'county');
            Log::write("区县商户分类：".json_encode($res), Log::DEBUG);

            //按城市获取配置的商户类型
            if(!$res){
                $res = D('Merchant')->getTermsList($city, 'city');
            }
            Log::write("城市商户分类：".json_encode($res), Log::DEBUG);

            //按省份获取配置的商户类型
            if(!$res){
                $res = D('Merchant')->getTermsList($province, 'provice');
            }
            Log::write("省份商户分类：".json_encode($res), Log::DEBUG);

            //以上方式都没配置，则按默认的全国方式获取配置的商户类型
            if(!$res){
                $res = D('Merchant')->getTermsList();
            }
            Log::write("默认商户分类：".json_encode($res), Log::DEBUG);

            //如果系统没有配置数据,正常情况下，该异常不会发生
            if(!$res){
                BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
            }

            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['img_url'] = C('ADMIN_SERVER_HOST');
            $ret['data'] = $res;
        }catch (BusinessException $e){
            $ret = ['code'=>$e->getCode(), 'msg'=>$e->getMessage()];
        }
        Response::format($ret);
        $this->ajaxReturn($ret);
    }


 /**趣提钱轮播图**/
    public function getCarousels()
    {
        try{
         $data = M("AdminSlide")->where("slide_status = 1")->select();
         $arr = [];
         foreach ($data as $key => $value) {
           $arr[$key]['slide_id'] = $value['slide_id'];
           $arr[$key]['slide_url'] = C('IMAGE_PATH').$value['slide_pic'];
           $arr[$key]['aurl'] = $value['slide_url'];
         }
         $ret = Constant::getReturn(Constant::SUCCESS);
         $ret['data'] = $arr;
        }catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
       
    }

    
}
